import pymysql


def main():
    # 1、创建连接对象
    conn = pymysql.connect(host='106.15.205.83', port=3306,
                           user='kfx1997', password='1234QWEasd',
                           db='school', charset='utf8',
                           cursorclass=pymysql.cursors.DictCursor)
    try:
        # 2、获取游标对象
        with conn.cursor() as cursor:  # with ... as ... 上下文语法, 结束自动关闭, with open 一样
            # 3、执行SQL得到的结果
            cursor.execute('select stuid as 学号,stuname as 姓名,stusex as 性别,stubrith as 生日 from tb_student')
            print(cursor.fetchone())  # 读取一行
            print(cursor.fetchall())  # 读取（游标之后的）所有
            """结论：
            1、可以指定字典游标，使用参数cursorclass=pymysql.cursors.DictCursor
            2、可以将字段取别名
            """
    except pymysql.MySQLError as error:
        print(error)
    finally:
        # 4、关闭连接，释放资源，没有上下文语法的支持
        conn.close()


if __name__ == '__main__':
    main()
